/******************************************************************************

 @file packet_transmission.c

 @brief Packet Transmission Module for TI 15.4-Stack Sensor Example

 *****************************************************************************/

#include "packet_transmission.h"
#include "smsgs.h"
#include "ssf.h"
#include "sensor.h"
#include "util_timer.h"
#include <ti/display/Display.h>
#include <pthread.h>
#include <mqueue.h>
#include "mac_util.h"
#include "ssf.h"
#include "api_mac.h"
#include <ti/drivers/dpl/EventP.h>

#define RAW_SEND_POLL_INTERVAL 300  // 发送轮询间隔
#define RAW_SEND_TIMEOUT 5000  // 发送超时时间
#define PACKET_SEND_INTERVAL 15  // 发送包之间的间隔时间（ms）
#define PACKET_SEND_FAIL_COUNT_MAX 5  // 发送失败次数最大值

#define TAG "PacketTx"
#ifndef DEBUG_PRINT_ENABLE
#define DEBUG_PRINT_ENABLE 1
#endif
#if DEBUG_PRINT_ENABLE
// Macro for debug print with file, function, and line number
// #define DEBUG_PRINT(fmt, ...) \
//     Display_printf(display, 0, 0, "[%s:%d:%s] " fmt, TAG, __LINE__, __FUNCTION__, ##__VA_ARGS__)
#define DEBUG_PRINT(fmt, ...) \
    Display_printf(display, 0, 0, "[%s:%d] " fmt, TAG, __LINE__, ##__VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...)
#endif

typedef struct {
    uint8_t lostPacketNum;  // 丢包数量，0表示没有丢包
    uint16_t *lostPacketArray;  // 丢包序号数组，NULL表示没有丢包
} lostPacketQueueItem_t;

// static uint8_t  g_rawDataBuffer[1000];
static uint8_t  *g_rawData=NULL;
static uint32_t g_rawDataLen;
static uint16_t g_packetTotal;
static uint16_t g_packetIndex = 0;
static uint16_t g_packetSize = 0;
static rawTxState_t g_rawTxState = 0;
static uint16_t g_packetSendFailCount = 0;

static mqd_t g_mqdLostPacketIndexes = NULL;
static ClockP_Struct rawSendClkStruct;
static ClockP_Handle rawSendClkHandle;

// EventP for raw transmission state
static EventP_Struct rawTxStateEventStruct;
static EventP_Handle rawTxStateEvent = NULL;

extern Display_Handle display;
extern uint16_t Sensor_events;
extern bool Sensor_sendMsg(Smsgs_cmdIds_t type, ApiMac_sAddr_t *pDstAddr,
                    bool rxOnIdle, uint16_t len, uint8_t *pData);

static void processRawSendTimeoutCallback(uintptr_t a0);
static void initializeRawSendTimeoutClock(void);
static void setRawSendTimeoutClock(uint32_t rawSendTimeout);
static void stopRawTx(void);
static void postRawTxStateEvent(rawTxState_t state);
static void handleSendError(rawTxState_t nextState);
static void updatePollByState(rawTxState_t state);
static void updateTimeoutByState(rawTxState_t state);


/*!
 * @brief 根据状态自动更新poll设置
 * 简化poll管理，避免手动调用_set_poll
 */
static void updatePollByState(rawTxState_t state)
{
    static rawTxState_t lastState = RAW_TX_STATE_IDLE;
    static bool pollFastMode = false;
    
    // 需要快速poll的状态
    bool needFastPoll = (state == RAW_TX_STATE_WAIT_START_RESP || 
                         state == RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP);
    
    // 需要正常poll的状态（发送数据时不需要快速poll）
    bool needNormalPoll = (state == RAW_TX_STATE_SENDING || 
                          state == RAW_TX_STATE_LOST_PACKET_SENDING ||
                          state == RAW_TX_STATE_IDLE || 
                          state == RAW_TX_STATE_ERROR);
    
    // 状态变化时才更新poll
    if(lastState != state) {
        if(needFastPoll && !pollFastMode) {
            // 切换到快速poll
            Jdllc_setPollRate(RAW_SEND_POLL_INTERVAL);
            Ssf_setPollClock(RAW_SEND_POLL_INTERVAL);
            pollFastMode = true;
            // DEBUG_PRINT("Set fast poll: %d", RAW_SEND_POLL_INTERVAL);
        }
        else if(needNormalPoll && pollFastMode) {
            // 恢复到正常poll
            const Smsgs_configReqMsg_t* configSettings = Sensor_getConfigSettings();
            if(configSettings != NULL) {
                Jdllc_setPollRate(configSettings->pollingInterval);
                Ssf_setPollClock(configSettings->pollingInterval);
                pollFastMode = false;
                // DEBUG_PRINT("Set normal poll: %d", configSettings->pollingInterval);
            }
        }
        lastState = state;
    }
}

/*!
 * @brief 根据状态自动更新超时时钟设置
 * 简化超时管理，避免手动调用setRawSendTimeoutClock
 * @param state - 当前状态
 */
static void updateTimeoutByState(rawTxState_t state)
{
    // static rawTxState_t lastState = RAW_TX_STATE_IDLE;
    
    switch(state) {
        case RAW_TX_STATE_IDLE:
        case RAW_TX_STATE_ERROR:
            // 空闲和错误状态，清除超时
            setRawSendTimeoutClock(0);
            break;
            
        case RAW_TX_STATE_START:
            // 开始状态,可能是传感器忙，需要设置超时
            setRawSendTimeoutClock(RAW_SEND_TIMEOUT);
            break;
            
        case RAW_TX_STATE_WAIT_START_RESP:
            // 等待开始响应，设置长超时
            // if(lastState != state) {
                setRawSendTimeoutClock(RAW_SEND_TIMEOUT);
                // DEBUG_PRINT("Set timeout for WAIT_START_RESP: %d", RAW_SEND_TIMEOUT);
            // } 
            // else if(!packetSent) {
            //     // 如果不是状态转换且packetSent为false，说明收到响应，清除超时
            //     setRawSendTimeoutClock(0);
            // }
            break;
            
        case RAW_TX_STATE_SENDING:
            // 发送状态，如果刚发送了包，设置发送间隔
            // if(packetSent) {
                setRawSendTimeoutClock(PACKET_SEND_INTERVAL);
                // DEBUG_PRINT("Set send interval: %d", PACKET_SEND_INTERVAL);
            // } 
            // else if(g_packetIndex >= g_packetTotal) {
            //     // 所有包发送完成，清除超时
            //     setRawSendTimeoutClock(0);
            // }
            break;
            
        case RAW_TX_STATE_ACK_COMPLETE:
            // ACK完成状态，设置长超时等待ACK响应
            // if(lastState != state) {
                setRawSendTimeoutClock(RAW_SEND_TIMEOUT);
                // DEBUG_PRINT("Set timeout for ACK_COMPLETE: %d", RAW_SEND_TIMEOUT);
            // }
            break;
            
        case RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP:
            // 等待ACK响应，清除超时（响应已收到）
            setRawSendTimeoutClock(0);
            break;
            
        case RAW_TX_STATE_LOST_PACKET_SENDING:
            // 丢包重发状态，如果刚发送了包，设置发送间隔
            // if(packetSent) {
                setRawSendTimeoutClock(PACKET_SEND_INTERVAL);
                // DEBUG_PRINT("Set retry send interval: %d", PACKET_SEND_INTERVAL);
            // } 
            // else {
            //     // 没有包要发送，清除超时
            //     setRawSendTimeoutClock(0);
            // }
            break;
            
        default:
            break;
    }
    
    // lastState = state;
}

/*!
 * @brief 统一的错误处理函数
 * 自动恢复poll并设置错误状态
 */
static void handleSendError(rawTxState_t nextState)
{
    DEBUG_PRINT("Send error, state: %d", g_rawTxState);
    postRawTxStateEvent(nextState);
    updateTimeoutByState(nextState);
}

static bool sendRawDataStartReq(uint32_t dataLen, uint8_t packetSize, uint16_t packetTotal)
{
    bool ret = false;
    uint8_t *pMsgBuf;
    uint8_t msgLen = 0;
    pMsgBuf = (uint8_t *)Ssf_malloc(16);
    if(pMsgBuf)
    {
        uint8_t *pBuf = pMsgBuf;
        *pBuf++ = (uint8_t)Smsgs_cmdIds_rampdata;
        msgLen++;
        pBuf  = Util_bufferUint16(pBuf,Smsgs_dataFields_startSendRawData);
        msgLen+=2;
        pBuf  = Util_bufferUint32(pBuf,dataLen);
        msgLen+=4;
        *pBuf++ = (uint8_t)packetSize;
        msgLen+=1;
        pBuf  = Util_bufferUint16(pBuf,packetTotal);
        msgLen+=2;
        ret = Sensor_sendMsg(Smsgs_cmdIds_rampdata, getCollectorAddr(), true,
                msgLen, pMsgBuf);
        Ssf_free(pMsgBuf);
    }
    return ret;
}

static bool sendAckRawDataCompleteReq(uint16_t packetIndex, uint16_t maxPacketIndex)
{
    bool ret = false;
    uint8_t *pMsgBuf;
    uint8_t msgLen = 0;
    pMsgBuf = (uint8_t *)Ssf_malloc(16);
    if(pMsgBuf)
    {
        uint8_t *pBuf = pMsgBuf;
        *pBuf++ = (uint8_t)Smsgs_cmdIds_rampdata;
        msgLen++;
        pBuf  = Util_bufferUint16(pBuf,Smsgs_dataFields_ackRawDataComplete);
        msgLen+=2;
        pBuf = Util_bufferUint16(pBuf, packetIndex);
        msgLen += 2;
        pBuf = Util_bufferUint16(pBuf, maxPacketIndex);
        msgLen += 2;
        ret = Sensor_sendMsg(Smsgs_cmdIds_rampdata, getCollectorAddr(), true,
                msgLen, pMsgBuf);
        Ssf_free(pMsgBuf);
    }
    return ret;
}

static bool sendRawDataReq(uint16_t packetIndex, uint16_t packetTotal, uint8_t packetSize, uint32_t dataLen, uint8_t *rawData)
{
    bool ret = false;
    uint8_t *pMsgBuf;
    uint8_t msgLen = 0;
    pMsgBuf = (uint8_t *)Ssf_malloc(128);
    if(pMsgBuf)
    {
        uint8_t *pBuf = pMsgBuf;
        *pBuf++ = (uint8_t)Smsgs_cmdIds_rampdata;
        msgLen++;
        pBuf  = Util_bufferUint16(pBuf,Smsgs_dataFields_continuousSenRawdData);
        msgLen+=2;
        pBuf = Util_bufferUint16(pBuf, packetIndex);
        msgLen+=2;

        #if 0 // 测试用，生成模拟数据
        if(packetIndex == packetTotal - 1) {
            // 最后一包,计算最后一包的长度
            uint16_t lastPacketLen = dataLen - (packetSize * packetIndex);
            uint16_t basePos = packetIndex * packetSize;
            for(uint16_t i = 0; i < lastPacketLen; i++) {
                pBuf[i] = 0xAA;
            }
            msgLen += lastPacketLen;
        }else{
            // 不是最后一包，包长度为g_packetSize
            uint16_t basePos = packetIndex * packetSize;
            for(uint16_t i = 0; i < packetSize; i++) {
                pBuf[i] = 0xAA;
            }
            msgLen += packetSize;
        }
        #endif
        
        #if 1
        // 判断是不是最后一包 g_packetIndex ==  packetTotal - 1
        if(packetIndex == packetTotal - 1) {
            // 最后一包,计算最后一包的长度
            uint16_t lastPacketLen = dataLen - (packetSize * packetIndex);
            uint16_t basePos = packetIndex * packetSize;
            for(uint16_t i = 0; i < lastPacketLen; i++) {
                pBuf[i] = rawData[basePos + i];
            }
            msgLen += lastPacketLen;
        }else{
            // 不是最后一包，包长度为g_packetSize
            uint16_t basePos = packetIndex * packetSize;
            for(uint16_t i = 0; i < packetSize; i++) {
                pBuf[i] = rawData[basePos + i];
            }
            msgLen += packetSize;
        }
        #endif
        ret = Sensor_sendMsg(Smsgs_cmdIds_rampdata, getCollectorAddr(), true,
                msgLen, pMsgBuf);
                
        Ssf_free(pMsgBuf);

    }
    return ret;
}

static void initializeRawSendTimeoutClock(void)
{
    rawSendClkHandle = UtilTimer_construct(&rawSendClkStruct,
                                        processRawSendTimeoutCallback,
                                        10,
                                        0,
                                        false,
                                        0);
}

static void setRawSendTimeoutClock(uint32_t rawSendTimeout)
{
    if(UtilTimer_isActive(&rawSendClkStruct) == true)
    {
        UtilTimer_stop(&rawSendClkStruct);
    }
    if ( rawSendTimeout )
    {
        UtilTimer_setTimeout(rawSendClkHandle, rawSendTimeout);
        UtilTimer_start(&rawSendClkStruct);
    }
}

static void processRawSendTimeoutCallback(uintptr_t a0)
{
    (void)a0;
    switch(g_rawTxState) {
        case RAW_TX_STATE_WAIT_START_RESP:
            // 等待开始传输响应超时，重新发送开始传输请求
            g_packetSendFailCount++;
            postRawTxStateEvent(RAW_TX_STATE_START);
            break;
        case RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP:
            // 等待ACK响应超时，重新发送ACK请求
            g_packetSendFailCount++;
            postRawTxStateEvent(RAW_TX_STATE_ACK_COMPLETE);
            break;
        case RAW_TX_STATE_SENDING:
            // 发送间隔超时，继续发送下一个包
            if(g_packetIndex < g_packetTotal) {
                // 还有包要发送，触发继续发送
            } else {
                // 所有包发送完成，进入ACK流程
                updateTimeoutByState(RAW_TX_STATE_ACK_COMPLETE);
                postRawTxStateEvent(RAW_TX_STATE_ACK_COMPLETE);
            }
            break;
        case RAW_TX_STATE_LOST_PACKET_SENDING:
            // 丢包重发间隔超时，继续发送下一个丢包
            break;
        case RAW_TX_STATE_ACK_COMPLETE:
        case RAW_TX_STATE_START:
            // 其他状态超时，重新发送数据
            break;
        default:
            break;
    }
    // 如果发送失败次数超过最大值，设置为错误状态
    if(g_packetSendFailCount > PACKET_SEND_FAIL_COUNT_MAX) {
        postRawTxStateEvent(RAW_TX_STATE_ERROR);
    }
    Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
    Ssf_PostAppSem();
}


/*!
 * @brief 统一的发送数据包函数（用于正常发送和重发）
 * @param packetIndex - 要发送的包序号
 * @return true-发送成功，false-发送失败
 */
static bool sendPacketWithRetry(uint16_t packetIndex)
{
    if(true != sendRawDataReq(packetIndex, g_packetTotal, g_packetSize, g_rawDataLen, g_rawData)) {
        DEBUG_PRINT("Packet[%d] send failed", packetIndex);
        return false;
    }
    return true;
}

void PacketTransmission_processSensorRawTxMsgEvt(void)
{
    static lostPacketQueueItem_t lostPacket = {0};
    static uint8_t lostPacketIndex = 0;
    
    Util_clearEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT); //清除事件
    
    switch(g_rawTxState) {
        case RAW_TX_STATE_ERROR:
        case RAW_TX_STATE_IDLE:
            DEBUG_PRINT("RAW_TX_STATE_%s", 
                       g_rawTxState == RAW_TX_STATE_ERROR ? "ERROR" : "IDLE");
            stopRawTx();
            break;
            
        case RAW_TX_STATE_START:
            DEBUG_PRINT("RAW_TX_STATE_START");
            if(g_packetTotal > 0) {
                sendRawDataStartReq(g_rawDataLen, g_packetSize, g_packetTotal);
                postRawTxStateEvent(RAW_TX_STATE_WAIT_START_RESP);
                updateTimeoutByState(RAW_TX_STATE_WAIT_START_RESP);
            } else {
                postRawTxStateEvent(RAW_TX_STATE_IDLE);
            }
            break;
            
        case RAW_TX_STATE_WAIT_START_RESP:
            // 在 PacketTransmission_processRampResp() 中处理响应
            break;
            
        case RAW_TX_STATE_SENDING:
            g_packetSendFailCount = 0;  // 重置失败计数
            if(g_packetIndex < g_packetTotal) {
                // 发送当前包
                if(sendPacketWithRetry(g_packetIndex)) {
                    // 发送成功，更新索引，通过超时回调控制发送节奏
                    g_packetIndex++;
                }
                updateTimeoutByState(RAW_TX_STATE_SENDING);
            } else {
                // 所有包发送完成，进入ACK流程
                updateTimeoutByState(RAW_TX_STATE_ACK_COMPLETE);
                postRawTxStateEvent(RAW_TX_STATE_ACK_COMPLETE);
                Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
                Ssf_PostAppSem();
            }
            break;
            
        case RAW_TX_STATE_ACK_COMPLETE:
            DEBUG_PRINT("RAW_TX_STATE_ACK_COMPLETE");
            updateTimeoutByState(RAW_TX_STATE_ACK_COMPLETE);
            if(!sendAckRawDataCompleteReq(g_packetIndex, g_packetTotal)) {
                DEBUG_PRINT("sendAckRawDataCompleteReq failed");
                return;
            }
            postRawTxStateEvent(RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP);
            break;
            
        case RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP: {
            g_packetSendFailCount = 0;
            unsigned int priority;
            
            if(mq_receive(g_mqdLostPacketIndexes, (void *)&lostPacket, 
                         sizeof(lostPacket), &priority) >= 0) {
                DEBUG_PRINT("Lost packets: %d", lostPacket.lostPacketNum);
                
                if(lostPacket.lostPacketNum == 0) {
                    // 没有丢包
                    if(g_packetIndex >= g_packetTotal) {
                        updateTimeoutByState(RAW_TX_STATE_IDLE);
                        postRawTxStateEvent(RAW_TX_STATE_IDLE);
                    } else {
                        updateTimeoutByState(RAW_TX_STATE_SENDING);
                        postRawTxStateEvent(RAW_TX_STATE_SENDING);
                    }
                } else {
                    // 有丢包，进入重发流程
                    lostPacketIndex = 0;
                    updateTimeoutByState(RAW_TX_STATE_LOST_PACKET_SENDING);
                    postRawTxStateEvent(RAW_TX_STATE_LOST_PACKET_SENDING);
                }
            } else {
                // 队列为空，异常情况，安全退出
                DEBUG_PRINT("Queue empty, stopping");
                handleSendError(RAW_TX_STATE_IDLE);
            }
            Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
            Ssf_PostAppSem();
            break;
        }
            
        case RAW_TX_STATE_LOST_PACKET_SENDING: {
            // 确保有有效的丢包信息
            if(lostPacket.lostPacketArray == NULL || lostPacket.lostPacketNum == 0) {
                DEBUG_PRINT("Invalid lost packet info, resetting");
                if(lostPacket.lostPacketArray != NULL) {
                    Ssf_free(lostPacket.lostPacketArray);
                    lostPacket.lostPacketArray = NULL;
                }
                updateTimeoutByState(RAW_TX_STATE_SENDING);
                postRawTxStateEvent(RAW_TX_STATE_SENDING);
            }
            
            // 发送丢包，使用间隔时钟控制节奏
            else if(lostPacketIndex < lostPacket.lostPacketNum) {
                uint16_t retryIndex = lostPacket.lostPacketArray[lostPacketIndex];
                if(sendPacketWithRetry(retryIndex)) {
                    // 发送成功，更新索引，通过超时回调控制发送节奏
                    lostPacketIndex++;
                }
                updateTimeoutByState(RAW_TX_STATE_LOST_PACKET_SENDING);
                break;
            }
            
            // 检查是否完成所有丢包重发
            else if(lostPacketIndex >= lostPacket.lostPacketNum) {
                // 释放当前丢包数组内存
                Ssf_free(lostPacket.lostPacketArray);
                lostPacket.lostPacketArray = NULL;
                lostPacket.lostPacketNum = 0;
                
                // 没有更多丢包，继续发送剩余数据
                updateTimeoutByState(RAW_TX_STATE_SENDING);
                postRawTxStateEvent(RAW_TX_STATE_SENDING);
            }
            Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
            Ssf_PostAppSem();
            break;
        }
    }
}

/*
 * @brief 解析丢包重发命令
 *
 * @param pBuf - 指向命令数据的指针
 * @param len - 数据长度
 */
void PacketTransmission_processRampResp(ApiMac_mcpsDataInd_t *pDataInd)
{
    uint8_t *pBuf = pDataInd->msdu.p;
    uint8_t cmdId;
    uint16_t frameControl;
    uint16_t lostPacketNum;
    uint16_t *lostPacketIndexes=NULL;
    uint8_t i;
    lostPacketQueueItem_t lostPacket;

    /* Parse the message */
    cmdId = (Smsgs_cmdIds_t)*pBuf++;
    frameControl = Util_parseUint16(pBuf);
    pBuf += 2;

    if(frameControl == Smsgs_dataFields_startSendRawData) {
        /* Make sure the message is the correct size */
        if(pDataInd->msdu.len < 4)
        {
            DEBUG_PRINT("Invalid start msg");
            return;
        }
        if(g_rawTxState == RAW_TX_STATE_WAIT_START_RESP) {
            uint8_t isBusy = *pBuf++;
            if(isBusy == 1) {
                DEBUG_PRINT("Sensor is busy");
                // 传感器忙，等待超时后重新发送开始传输请求，不计入错误次数
                updateTimeoutByState(RAW_TX_STATE_START);
                postRawTxStateEvent(RAW_TX_STATE_START);
            }
            else{
                // 收到开始传输响应，开始传输数据
                DEBUG_PRINT("Start send data");
                updateTimeoutByState(RAW_TX_STATE_SENDING);
                postRawTxStateEvent(RAW_TX_STATE_SENDING);
                Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
                Ssf_PostAppSem();
            }
        }
        else{
            DEBUG_PRINT("Invalid state %d", g_rawTxState);
        }
    }

    /* 确认是丢包重发命令 */
    else if(frameControl == Smsgs_dataFields_reSendRawData) {
        /* Make sure the message is the correct size */
        if(pDataInd->msdu.len < 4)
        {
            DEBUG_PRINT("Invalid msg len");
            return;
        }
        if(g_rawTxState == RAW_TX_STATE_WAIT_ACK_COMPLETE_RESP)  {

                /* 获取丢包数量 */
                lostPacketNum = *pBuf++;
                DEBUG_PRINT("Lost count: %d", lostPacketNum);

                /* 如果没有丢包则直接返回 */
                if(lostPacketNum == 0) {
                    goto SEND_ACK;
                }

                /* 分配内存存储丢包序号 */
                lostPacketIndexes = (uint16_t *)Ssf_malloc(lostPacketNum * sizeof(uint16_t));
                if(lostPacketIndexes == NULL) {
                    DEBUG_PRINT("Malloc failed for %d packets", lostPacketNum);
                    return;
                }

                /* 解析所有丢失的包序号 */ 
                for(i = 0; i < lostPacketNum; i++) {
                    lostPacketIndexes[i] = Util_parseUint16(pBuf);
                    pBuf += 2;
                    DEBUG_PRINT("Lost[%d]=%d", i, lostPacketIndexes[i]);
                }

        SEND_ACK:
                lostPacket.lostPacketNum = lostPacketNum;
                lostPacket.lostPacketArray = lostPacketIndexes;
                if(mq_send(g_mqdLostPacketIndexes, (void *)&lostPacket, sizeof(lostPacket), 1) == -1) {
                    DEBUG_PRINT("Queue send failed, free memory");
                    // 队列满时释放内存，避免泄漏
                    if(lostPacketNum > 0 && lostPacketIndexes != NULL) {
                        Ssf_free(lostPacketIndexes);
                    }
                    // 等待超时重发请求
                }
                Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
                Ssf_PostAppSem();   
            }
            else{
                DEBUG_PRINT("Invalid state %d", g_rawTxState);
            }
        }

}


rawTxState_t PacketTransmission_getRawTxState(void)
{
    return g_rawTxState;
}

/*!
 * @brief       Post raw tx state event, and update poll and timeout.
 * @param state - 状态
 */
static void postRawTxStateEvent(rawTxState_t state)
{
    g_rawTxState = state;

    // 根据状态自动更新poll设置
    updatePollByState(state);

    if(rawTxStateEvent != NULL)
    {
        EventP_clear(rawTxStateEvent, 0xFFFFFFFF);
        // 发布事件，事件值为状态值（每个状态对应一个bit）
        EventP_post(rawTxStateEvent, (1U << state));
    }
}

/*!
 * @brief       Get raw tx state event bit.
 */
uint32_t PacketTransmission_getRawTxStateEventHandle(void)
{
    if(rawTxStateEvent == NULL)
    {
        return 0;
    }
    return EventP_get(rawTxStateEvent);
}

/*!
 * @brief       wait raw tx state event bit.
 */
uint32_t PacketTransmission_waitRawTxStateEventBit(uint32_t eventMask, uint32_t timeout)
{
    if(rawTxStateEvent == NULL)
    {
        return 0;
    }
    return EventP_pend(rawTxStateEvent, eventMask, false, timeout );
}

/*!
 * @brief       Get packet index.
 */
uint16_t PacketTransmission_getPacketIndex(void)
{
    return g_packetIndex;
}

uint16_t PacketTransmission_getPacketTotal(void)
{
    return g_packetTotal;
}

EventP_Handle PacketTransmission_getRawTxStateEvent(void)
{
    return rawTxStateEvent;
}

void PacketTransmission_startRawTx(uint32_t dataLen, uint8_t *rawData, uint8_t packetSize)
{
    g_rawData = rawData;
    g_rawDataLen = dataLen;
    g_packetSize = packetSize;
    g_packetSendFailCount = 0;
    g_packetIndex = 0;
    g_packetTotal = (g_rawDataLen+g_packetSize-1) / g_packetSize;
    DEBUG_PRINT("g_packetIndex: %d, g_packetTotal: %d", g_packetIndex, g_packetTotal);

    postRawTxStateEvent(RAW_TX_STATE_START);
    Util_setEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
    Ssf_PostAppSem();

    // _set_poll(true);
}

/*!
 * @brief       Stop packet transmission.for internal use
 */
static void stopRawTx(void)
{
    Util_clearEvent(&Sensor_events, SENSOR_SEND_RAW_DATA_EVT);
    updateTimeoutByState(RAW_TX_STATE_IDLE);
    postRawTxStateEvent(RAW_TX_STATE_IDLE);
}

/*!
 * @brief       Stop packet transmission.for external use
 */
void PacketTransmission_stopRawTx(void)
{
    DEBUG_PRINT("Stopped");
    stopRawTx();
    Ssf_PostAppSem();
}

void PacketTransmission_init(void)
{
    static struct mq_attr myattr;
    myattr.mq_flags = O_NONBLOCK;
    myattr.mq_maxmsg = 10;
    myattr.mq_msgsize = sizeof(lostPacketQueueItem_t);
    myattr.mq_curmsgs = 0;
    g_mqdLostPacketIndexes = mq_open("/lostPacketIndexes", O_CREAT | O_RDWR, 0644, &myattr);
    if(g_mqdLostPacketIndexes == NULL)
    {
        DEBUG_PRINT("Queue init failed");
    }
    mq_setattr(g_mqdLostPacketIndexes, &myattr, NULL);
    initializeRawSendTimeoutClock();
    
    // Initialize EventP for raw transmission state
    rawTxStateEvent = EventP_construct(&rawTxStateEventStruct);
    if(rawTxStateEvent == NULL)
    {
        DEBUG_PRINT("Event init failed");
    }
    
    // Post initial state
    postRawTxStateEvent(RAW_TX_STATE_IDLE);
}
